package org.example;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigManager {
    private static final String CONFIG_PATH = "src/main/resources/config/settings.properties";
    static Logger logger = LoggerFactory.getLogger(ConfigManager.class);
    
    public static Properties loadConfig() {
        Properties props = new Properties();
        File configFile = new File(CONFIG_PATH);
        
        if (!configFile.exists()) {
            props = setDefaultValues(new Properties());
            saveConfig(props);
            logger.info("The configuration file does not exist, default configuration has been created");
            return props;
        }
        
        try (InputStream input = Files.newInputStream(Paths.get(CONFIG_PATH))) {
            props.load(input);
            logger.info("Successfully loaded configuration file");
        } catch (IOException e) {
            props = setDefaultValues(new Properties());
            logger.error("Configuration file loading failed, using default values");
        }
        return props;
    }

    private static Properties setDefaultValues(Properties props) {
        props.setProperty("trayIconPath", "resources/images/tray_icon.png"); // 图标路径配置
        props.setProperty("salary", "8000");
        props.setProperty("salaryType", "月");
        props.setProperty("dailyWorkHours", "8");
        props.setProperty("monthlyWorkDays", "21.75");
        return props;
    }

    public static void saveConfig(Properties props) {
        new File("src/main/resources/config").mkdirs();
        
        try (OutputStream output = new FileOutputStream(CONFIG_PATH)) {
            props.store(output, "Salary Calculator Configuration");
            logger.info("The configuration file has been successfully saved ！！！");
        } catch (IOException e) {
            logger.error("Configuration save failed: " + e.getMessage());
        }
    }
}